import requests
import re
import json
import os
from tqdm import tqdm  # 进度条配置

headers = {
    'referer': 'https://www.bilibili.com/',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.560'
}
url = "https://www.bilibili.com/video/BV1f8411d7hQ/?spm_id_from=333.337.search-card.all.click"
response = requests.get(url=url, headers=headers)
title = re.findall('<h1 title="(.*?)"', response.text)[0]
title = re.sub(r"[\/:*?<>|]", "", title)
print("视频标题为：", title)

html_data = re.findall('<script>window.__playinfo__=(.*?)</script>', response.text)[0]
json_data = json.loads(html_data)

# 获取音频链接
audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
# 获取视频链接
video_url = json_data['data']['dash']['video'][0]['baseUrl']

# 获取视频
video_content = requests.get(video_url, stream=True)
# 获取视频大小
file_size = int(video_content.headers.get('Content-Length'))
# 初始化进度条
video_pbar = tqdm(total=file_size)
# 保存视频
with open(f'{title}.mp4', mode='wb') as f:
    # 把视频分成 1024 * 1024 * 2 为等分的大小 进行遍历
    for video_chunk in video_content.iter_content(1024 * 1024 * 2):
        # 写入数据
        f.write(video_chunk)
        # 更新进度条
        video_pbar.set_description(f'正在下载{title}视频中......')
        # 更新进度条长度
        video_pbar.update(1024 * 1024 * 2)
    # 下载完毕
    video_pbar.set_description('下载完成！')
    # 关闭进度条
    video_pbar.close()

# 获取音频
audio_content = requests.get(audio_url, stream=True)
file_size = int(audio_content.headers.get('Content-Length'))
audio_pbar = tqdm(total=file_size)
# 保存音频
with open(f'{title}.mp3', mode='wb') as f:
    for audio_chunk in audio_content.iter_content(1024 * 1024 * 2):
        f.write(audio_chunk)
        audio_pbar.set_description(f'正在下载{title}音频中......')
        audio_pbar.update(1024 * 1024 * 2)
    audio_pbar.set_description('下载完成！')
    audio_pbar.close()


def merge(title):
    ffmpeg = r'E:\ffmpeg\bin\ffmpeg.exe -i ' + title + '.mp4 -i ' + title + '.mp3 -acodec copy -vcodec copy ' + title + '-out.mp4'
    os.popen(ffmpeg)
    #os.remove(f'{title}.mp3')
    #os.remove(f'{title}.mp4')


# 合并音视频
merge(title)
